package com.gillion.grape.fros.ui.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;

import com.gillion.grape.core.Logger;
import com.gillion.grape.core.utils.Utils;


public class FileUtil {

	private static Log logger = LogFactory.getLog(FileUtil.class);

	public static void deleteSVNFile(File file) throws Exception {
		if (file.isFile()) {
			// System.out.println("File :" + file.getAbsolutePath());
		} else {
			// System.out.println("Dir :" + file.getAbsolutePath());
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				deleteSVNFile(files[i]);
				if (files[i].getName().equals(".svn")) {
					FileUtils.deleteDirectory(files[i]);
					logger.debug("閸掔娀娅庨弬鍥︽:" + files[i].getPath());
				}
			}
		}
	}

	/**
	 * 鏉烆剙瀵叉稉铏硅娴煎皷锟芥竷om.grape.xxx閳ユ繄娈戠捄顖氱窞
	 */
	public static String toPackageString(String string) {
		string = string.replaceAll("\\\\", "/");
		String[] strs = string.split("/");
		StringBuilder sb = new StringBuilder();
		for (String str : strs) {
			sb.append(str).append(".");
		}
		string = sb.toString();
		return string.substring(0, string.length() - 1);
	}

	/**
	 * 鏉烆剙瀵叉稉铏硅娴硷拷"/com/grape/xxx"閻ㄥ嫯鐭惧锟�
	 */
	public static String toFilePathString(String string) {
		String[] strs = string.split(".");
		StringBuilder sb = new StringBuilder();
		for (String str : strs) {
			sb.append(File.separator).append(str).append(File.separator);
		}
		return sb.toString();
	}

	public static void copyFile(File fromFile, File toFile) {
		try {
			FileInputStream fis = new FileInputStream(fromFile);
			FileOutputStream fos = new FileOutputStream(toFile);
			byte[] buf = new byte[1024];
			int i = 0;
			while ((i = fis.read(buf)) != -1) {
				fos.write(buf, 0, i);
			}
			fis.close();
			fos.close();
		} catch (Exception ex) {
			throw new RuntimeException("error");
		}
	}

	public static void copyDir(File sourceDir, File destDir, String excludedDirName) throws IOException {
		copyDir(sourceDir, destDir, true, excludedDirName);
	}

	public static void copyDir(File from, File to) throws IOException {
		copyDir(from, to, true, null);
	}

	public static void copyDir(File from, File to, boolean includeSubdirs) throws IOException {
		copyDir(from, to, includeSubdirs, null);
	}

	public static void copyDir(File from, File to, boolean includeSubdirs, String excludedDirName) throws IOException {
		if (!to.exists())
			to.mkdirs();
		if (from == null || !from.isDirectory() || !to.isDirectory())
			return;
		File fs[] = from.listFiles();
		if (fs == null)
			return;
		for (int i = 0; i < fs.length; i++) {
			String n = fs[i].getName();
			File c = new File(to, n);
			if (!fs[i].isDirectory() || includeSubdirs)
				if (fs[i].isDirectory()) {
					if (!fs[i].getName().equals(excludedDirName)) {
						c.mkdirs();
						copyDir(fs[i], c, includeSubdirs, excludedDirName);
					}
				} else {
					copyFileOrDirectory(fs[i], to);
				}
		}

	}

	public static void copyFileOrDirectory(File sourceFile, File destDir) throws IOException {
		String name = sourceFile.getName();
		File destFile = new File(destDir, name);
		if (sourceFile.isDirectory()) {
			destFile.mkdirs();
			return;
		}
		InputStream in = new FileInputStream(sourceFile);
		OutputStream out = new FileOutputStream(destFile);
		try {
			copy(in, out);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (in != null)
				in.close();
			if (out != null)
				out.close();
		}
		return;
	}

	public static void copy(InputStream in, OutputStream out) throws IOException {
		byte buf[] = new byte[1024];
		for (int len = 0; (len = in.read(buf, 0, buf.length)) != -1;)
			out.write(buf, 0, len);
	}

	public static boolean writeFile(InputStream content, IFile targetFile) {
		try {
			if (targetFile.exists()) {
				targetFile.setContents(content, IFile.FORCE, new NullProgressMonitor());
			} else {
				String dir = Utils.getDirectory(targetFile.getFullPath().toString());
				IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(dir));
				Utils.createDerivedFolder(folder, true, true, null);
				targetFile.create(content, false, null);
			}
			Logger.logInfo(targetFile.getFullPath() + " 生成成功!");
			return true;
		} catch (CoreException e) {
			Logger.logError(e);
			return false;
		}
	}
}
